package cn.com.chengmandian.bike.controller;

import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.bike.dto.MemberLocationForm;
import cn.com.chengmandian.bike.model.vo.GeocoderVo;
import cn.com.chengmandian.core.redis.cache.AgentParamCacheService;
import cn.com.chengmandian.core.redis.service.RedisService;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.pojo.BikeAreaParam;
import cn.com.chengmandian.core.web.pojo.BikeParam;
import cn.com.chengmandian.core.web.pojo.amap.RegeoCode;
import cn.com.chengmandian.core.web.service.AmapService;
import cn.com.chengmandian.core.web.service.OssService;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "通用接口!")
@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private OssService ossService;

    @Autowired
    private AmapService amapService;

    @Autowired
    private AgentParamCacheService agentParamCacheService;

    @Autowired
    private RedisService redisService;

    @ApiOperation("品牌参数(无需登录)")
    @GetMapping("/agent/config")
    public AjaxResult<Map<String, JSONObject>> agentConfig() {
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        JSONObject param = new JSONObject();
        BikeParam bikeParam = agentParamCacheService.getParam(agentInfo.getId());
        param.put("wxMiniQrcodePre", agentInfo.getWxMiniQrcodePre());
        param.put("bikeModel", agentInfo.getBikeModel());
        param.put("brandLogo", agentInfo.getLogo());
        param.put("brandName", agentInfo.getName());
        param.put("userPhoneAuthLogin",bikeParam.getUserPhoneAuthLogin());
        param.put("userServiceOnlineLink",bikeParam.getUserServiceOnlineLink());
        param.put("miniProgramOrderNotifyTemplateId", bikeParam.getMiniProgramOrderNotifyTemplateId());
        param.put("rideOrderWxPayScore",bikeParam.getRideOrderWxPayScore());
        param.put("wxOrderIsConfirm",bikeParam.getWxOrderIsConfirm());
        param.put("rideOrderPreSaleAmount",bikeParam.getRideOrderPreSaleAmount());
        param.put("rideOrderIsUseWxPayScore",bikeParam.getRideOrderIsUseWxPayScore());
        param.put("userRideFeedbackBillInformTemplateId", bikeParam.getUserRideFeedbackBillInformTemplateId());
        param.put("userAgentRideRealNameAuthEnabled", bikeParam.getUserAgentRideRealNameAuthEnabled());
        param.put("userAgentMiniLoginFaceAuthEnabled", bikeParam.getUserAgentMiniLoginFaceAuthEnabled());
        param.put("userAgentMinLoginFaceLifeAuthEnabled", bikeParam.getUserAgentMinLoginFaceLifeAuthEnabled());
        param.put("customerServiceDes", bikeParam.getCustomerServiceDes());
        param.put("miniHalfSizeAdEnabled", bikeParam.getMiniHalfSizeAdEnabled());
        param.put("miniHalfSizeAdAppId", bikeParam.getMiniHalfSizeAdAppId());
        param.put("miniHalfSizeAdLink", bikeParam.getMiniHalfSizeAdLink());
        List<String> list=new ArrayList<>();
        String userServicePhone="";
        userServicePhone=bikeParam.getUserServicePhone();
        String[] split = userServicePhone.split(";");
        for(int i=0;i< split.length;i++){
            list.add(split[i]);
        }
        //客服电话支持多个数组
        param.put("userServicePhone",list);
        Map<String, JSONObject> res = MapUtil.of("param", param);
        JSONObject baseData = new JSONObject();
        res.put("basedata", baseData);
        return AjaxResult.success(res);
    }

    @ApiOperation("配置参数(无需登录)")
    @GetMapping("/config")
    public AjaxResult<Map<String, JSONObject>> config() {
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        JSONObject param = new JSONObject();
        BikeParam bikeParam = agentParamCacheService.getParam(agentInfo.getId());
        param.put("wxMiniQrcodePre", agentInfo.getWxMiniQrcodePre());
        param.put("bikeModel", agentInfo.getBikeModel());
        param.put("brandLogo", agentInfo.getLogo());
        param.put("brandName", agentInfo.getName());
        param.put("userPhoneAuthLogin",bikeParam.getUserPhoneAuthLogin());
        param.put("userServiceOnlineLink",bikeParam.getUserServiceOnlineLink());
        List<String> list=new ArrayList<>();
        param.put("miniProgramOrderNotifyTemplateId", bikeParam.getMiniProgramOrderNotifyTemplateId());
        param.put("rideOrderWxPayScore",bikeParam.getRideOrderWxPayScore());
        param.put("wxOrderIsConfirm",bikeParam.getWxOrderIsConfirm());
        param.put("rideOrderPreSaleAmount",bikeParam.getRideOrderPreSaleAmount());
        param.put("rideOrderIsUseWxPayScore",bikeParam.getRideOrderIsUseWxPayScore());
        param.put("userRideFeedbackBillInformTemplateId", bikeParam.getUserRideFeedbackBillInformTemplateId());
        param.put("userAgentRideRealNameAuthEnabled", bikeParam.getUserAgentRideRealNameAuthEnabled());
        param.put("userAgentMiniLoginFaceAuthEnabled", bikeParam.getUserAgentMiniLoginFaceAuthEnabled());
        param.put("userAgentMinLoginFaceLifeAuthEnabled", bikeParam.getUserAgentMinLoginFaceLifeAuthEnabled());
        param.put("customerServiceDes", bikeParam.getCustomerServiceDes());
        param.put("userIdentityAuthNotifyTemplateId", bikeParam.getUserIdentityAuthNotifyTemplateId());
        param.put("miniHalfSizeAdEnabled", bikeParam.getMiniHalfSizeAdEnabled());
        param.put("miniHalfSizeAdAppId", bikeParam.getMiniHalfSizeAdAppId());
        param.put("miniHalfSizeAdLink", bikeParam.getMiniHalfSizeAdLink());
        if (agentInfo.getAreaId() != null) {
            BikeAreaParam bikeAreaParam = agentParamCacheService.getParam(agentInfo.getId(), agentInfo.getAreaId());
            if (bikeAreaParam == null) {
                log.error("config bikeAreaParam error,agentId={}, areaId={}", agentInfo.getId(), agentInfo.getAreaId());
                return AjaxResult.error("服务初始化失败");
            }
            String userServicePhone="";
            if (StrUtil.isNotBlank(bikeAreaParam.getUserAreaServicePhone())) {
                userServicePhone=bikeAreaParam.getUserAreaServicePhone();
            }else{
                userServicePhone=bikeParam.getUserServicePhone();
            }
            String[] split = userServicePhone.split(";");
            for(int i=0;i< split.length;i++){
                list.add(split[i]);
            }
            //客服电话支持多个数组
            param.put("userServicePhone",list);
            if (StrUtil.isNotBlank(bikeAreaParam.getUserAreaServiceOnlineLink())) {
                param.put("userServiceOnlineLink",bikeAreaParam.getUserAreaServiceOnlineLink());
            }
            if(bikeAreaParam.getUserStaticCloseOrder() != null && bikeAreaParam.getUserStaticCloseOrder() > 0){
                param.put("userStaticCloseOrder",bikeAreaParam.getUserStaticCloseOrder());
            }
            if(StrUtil.isNotBlank(bikeAreaParam.getCustomerAreaServiceDes())) {
                param.put("customerServiceDes", bikeAreaParam.getCustomerAreaServiceDes());
            }
            param.put("userRideShareEnable", bikeAreaParam.getUserRideShareEnable());
            param.put("userRideRentEnable",bikeAreaParam.getUserRideRentEnable());
            param.put("userRideBuyMemberCard", bikeAreaParam.getUserRideBuyMemberCard());
            param.put("userNeedWareHelmetHintText", bikeAreaParam.getUserNeedWareHelmetHintText());
            param.put("userCameraAIStopBike", bikeAreaParam.getUserCameraAIStopBike());
            param.put("userCameraStopAngle", bikeAreaParam.getUserCameraStopAngle());
            param.put("userCameraStopDistance", bikeAreaParam.getUserCameraStopDistance());
            param.put("userCameraStopColor", bikeAreaParam.getUserCameraStopColor());
            param.put("userRideFaceAuthEnabled", bikeAreaParam.getUserRideFaceAuthEnabled());
            param.put("userMiniLoginFaceAuthEnabled", bikeAreaParam.getUserMiniLoginFaceAuthEnabled());
            param.put("userRideRealNameAuthEnabled", bikeAreaParam.getUserRideRealNameAuthEnabled());
            param.put("userMinLoginFaceLifeAuthEnabled", bikeAreaParam.getUserMinLoginFaceLifeAuthEnabled());
            param.put("userBikeHelmetLockStyle", bikeAreaParam.getUserBikeHelmetLockStyle());
            param.put("userRideStopBikeMaxTimesEnabled", bikeAreaParam.getUserRideStopBikeMaxTimesEnabled());
            param.put("userAutoCloseOrder", bikeAreaParam.getUserAutoCloseOrder());
        }
        Map<String, JSONObject> res = MapUtil.of("param", param);
        JSONObject baseData = new JSONObject();
        res.put("basedata", baseData);
        return AjaxResult.success(res);
    }

    @ApiOperation("用户图片上传(无需登录)")
    @PostMapping("/upload")
    public AjaxResult<Map<String, String>> upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "filePath", required = false) String model,
                                                  @RequestParam(value = "userCode", required = false) String userCode) {
        if(AuthUtil.getAgentUser() == null) {
            Assert.isTrue(StrUtil.isNotBlank(userCode), "缺少USER_CODE");
            String key = "CMD:BIKE:"+ LocalMapUtil.getAgentInfo().getId() + ":USERCODE:" + userCode;
            Assert.isTrue(redisService.hasKey(key), "缺少注册信息");
        }
        Assert.isTrue(!file.isEmpty(), "文件不存在");
        if(StrUtil.isBlank(model)){
            model = "other";
        }
        try {
            String extName = FileUtil.getSuffix(file.getOriginalFilename());
            String fileName = RandomUtil.randomString(32) + (StrUtil.isNotBlank(extName) ? ("." + extName) : "");
            String filePath = "files/user/"+model+ "/" + DateUtil.format(new Date(), "yyyyMM") + "/" + fileName;
            String url = ossService.putObject(filePath, file.getInputStream());
            return AjaxResult.success(MapUtil.of("url", url));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    @ApiOperation("坐标地址转换(无需登录)")
    @PostMapping("/geocoder")
    public AjaxResult<GeocoderVo> geocoder(@RequestBody MemberLocationForm memberLocationForm) {
        RegeoCode res = amapService.geocoder(memberLocationForm.getLat(), memberLocationForm.getLng());
        GeocoderVo geocoderVo = new GeocoderVo();
        geocoderVo.setAddress(res.getFormatted_address());
        JSONObject adInfo = new JSONObject();
        if (res.getAddressComponent().getCitycode() != null && res.getAddressComponent().getCitycode().length() <=3) {
            adInfo.put("city", res.getAddressComponent().getProvince());
        } else {
            adInfo.put("city", res.getAddressComponent().getCity());
        }
        geocoderVo.setAdInfo(adInfo);
        return AjaxResult.success(geocoderVo);
    }
}
